<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AttendanceStatistic extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'employee_id',
        'period_type',
        'period_date',
        'work_days',
        'actual_work_days',
        'absent_days',
        'leave_days',
        'late_count',
        'early_leave_count',
        'late_minutes',
        'early_leave_minutes',
        'overtime_hours',
        'overtime_minutes',
        'makeup_count',
        'approved_makeup_count',
        'annual_leave_days',
        'sick_leave_days',
        'personal_leave_days',
        'other_leave_days',
        'attendance_score',
        'total_work_hours',
        'standard_work_hours',
        'shift_count',
        'shift_details',
        'extra_statistics',
    ];

    protected $casts = [
        'period_date' => 'date',
        'attendance_score' => 'decimal:2',
        'shift_details' => 'array',
        'extra_statistics' => 'array',
    ];

    // 常量定义
    const PERIOD_DAILY = 'daily';
    const PERIOD_MONTHLY = 'monthly';
    const PERIOD_YEARLY = 'yearly';

    /**
     * 获取用户关系
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取员工关系
     */
    public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class);
    }

    /**
     * 获取考勤规则关系
     */
    public function attendanceRule(): BelongsTo
    {
        return $this->belongsTo(AttendanceRule::class);
    }

    /**
     * 作用域：按用户筛选
     */
    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * 作用域：按员工筛选
     */
    public function scopeByEmployee($query, $employeeId)
    {
        return $query->where('employee_id', $employeeId);
    }

    /**
     * 作用域：按周期类型筛选
     */
    public function scopeByPeriodType($query, $periodType)
    {
        return $query->where('period_type', $periodType);
    }

    /**
     * 作用域：按日期范围筛选
     */
    public function scopeByDateRange($query, $startDate, $endDate)
    {
        return $query->whereBetween('period_date', [$startDate, $endDate]);
    }

    /**
     * 作用域：按月份筛选
     */
    public function scopeByMonth($query, $year, $month)
    {
        return $query->where('period_type', self::PERIOD_MONTHLY)
                    ->whereYear('period_date', $year)
                    ->whereMonth('period_date', $month);
    }

    /**
     * 作用域：按年份筛选
     */
    public function scopeByYear($query, $year)
    {
        return $query->where('period_type', self::PERIOD_YEARLY)
                    ->whereYear('period_date', $year);
    }

    /**
     * 获取周期类型的显示名称
     */
    public function getPeriodTypeNameAttribute()
    {
        return match($this->period_type) {
            self::PERIOD_DAILY => '日',
            self::PERIOD_MONTHLY => '月',
            self::PERIOD_YEARLY => '年',
            default => '未知'
        };
    }

    /**
     * 计算出勤率
     */
    public function getAttendanceRateAttribute()
    {
        if ($this->work_days == 0) {
            return 0;
        }

        return round(($this->actual_work_days / $this->work_days) * 100, 2);
    }

    /**
     * 计算缺勤率
     */
    public function getAbsentRateAttribute()
    {
        if ($this->work_days == 0) {
            return 0;
        }

        return round(($this->absent_days / $this->work_days) * 100, 2);
    }

    /**
     * 计算迟到率
     */
    public function getLateRateAttribute()
    {
        if ($this->actual_work_days == 0) {
            return 0;
        }

        return round(($this->late_count / $this->actual_work_days) * 100, 2);
    }

    /**
     * 计算平均工作时长
     */
    public function getAverageWorkHoursAttribute()
    {
        if ($this->actual_work_days == 0) {
            return 0;
        }

        return round($this->total_work_hours / $this->actual_work_days, 2);
    }

    /**
     * 获取考勤等级
     */
    public function getAttendanceGradeAttribute()
    {
        $score = $this->attendance_score;

        if ($score >= 95) {
            return '优秀';
        } elseif ($score >= 85) {
            return '良好';
        } elseif ($score >= 75) {
            return '一般';
        } elseif ($score >= 60) {
            return '合格';
        } else {
            return '不合格';
        }
    }

    /**
     * 计算总请假天数
     */
    public function getTotalLeaveDaysAttribute()
    {
        return $this->annual_leave_days +
               $this->sick_leave_days +
               $this->personal_leave_days +
               $this->other_leave_days;
    }

    /**
     * 计算总加班时长（小时）
     */
    public function getTotalOvertimeHoursAttribute()
    {
        return $this->overtime_hours + round($this->overtime_minutes / 60, 2);
    }

    /**
     * 检查是否有异常
     */
    public function hasExceptions()
    {
        return $this->late_count > 0 ||
               $this->early_leave_count > 0 ||
               $this->absent_days > 0 ||
               $this->makeup_count > 0;
    }
}
